<?php
/**
 * LICENSE
 * 
 * [license information]
 * 
 * @category   BKPay
 * @copyright  Copyright (c) 2011 bkpay.vn
 * @license    http://license.bkpay.vn
 * @version    v 1.0 2011-09-19
 * @author	   hoaihuong@9webdesigns.com, s50702790@gmail.com
 */
require_once 'libs/BKPay/Constant.php';
class BKPay_Security_Server {
	
	public $config;
	/**
	 * Contructor
	 */
	public function __construct() {
		if (is_file('secureconfig.php')) {
			$this->config =  include_once 'secureconfig.php';
		}
	}
	/**
	 * Decrypt PKCS7
	 */
	public function decryptPKCS7($encryptedData)
	{
//		$this->config['passwordKeyFile'] = "bkdragon89";
		$public = file_get_contents($this->config['myCertFile']);
		$private = array(file_get_contents($this->config['myKeyFile']), $this->config['passwordKeyFile']);
		
		// decrypt with PKCS7
		try{
			
			$result = openssl_pkcs7_decrypt($this->config['filePath'] . "verified.txt", $this->config['filePath'] . "decrypted.txt", $public, $private);
			
			if($result == true) { 
				return file_get_contents($this->config['filePath'] . "decrypted.txt");
			}
			else {
				return null;   
			}
		// Decryption successful
		// return file_get_contents($root."/encrypt/message/out.txt");
		   
		} catch (Exception $e) {
		    // Decryption failed
		    throw $e;  
		}
	}
	
	/**
	 * Verify Signed data
	 */
	public function verifyPKCS7($signedData){
		try{
			//write signedData in file
			$fp = fopen($this->config['filePath'] . "signed.txt", "w");
			fwrite($fp, $signedData);
			fclose($fp);
			//verify
			
			$result = openssl_pkcs7_verify ( 
									$this->config['filePath'] . "signed.txt", 
									PKCS7_DETACHED, 
									$this->config['filePath'] . "CerKey.txt", 
									array (realpath($this->config['myCertFile'])) ,
									realpath($this->config['bkpayCertFile']),
									$this->config['filePath'] . "verified.txt" 
								);
			if($result == 1) {
				return true;
			}
			else {
				return false;
			}
			
		} catch ( Exception $e ) {
			throw $e;
		}
	}
}

